﻿// Shader-Based-Image-Processing (SBIP)
// http://code.google.com/p/sbip/
//
// Copyright © Frank Nagl, 2009-2011
// admin@franknagl.de
//
namespace SBIP.Helper
{
    /// <summary> Polygon helper methods. </summary>
    public class Polygon
    {
        /// <summary>
        /// The function will return YES if the point x,y is inside the polygon, or
        /// NO if it is not.  If the point is exactly on the edge of the polygon,
        /// then the function may return YES or NO.        
        ///Note that division by zero is avoided because the division is 
        /// protected by the "if" clause which surrounds it.
        /// </summary>
        /// <remarks>Original C code from http://alienryderflex.com/polygon/
        /// </remarks>
        /// <param name="x">The x coordinate of point to be tested.</param>
        /// <param name="y">The y coordinate of point to be tested.</param>
        /// <param name="polySides">How many corners the polygon has.</param>
        /// <param name="polyX">Horizontal coordinates of corners.</param>
        /// <param name="polyY">Vertical coordinates of corners.</param>
        /// <returns>True, if the point is inside the polygon, otherwise false.
        /// </returns>
        public static bool PointInPolygon(
            float x, float y, int polySides, float[] polyX, float[] polyY)
        {
            int i, j = polySides - 1;
            bool oddNodes = false;

            for (i = 0; i < polySides; i++)
            {
                if ((polyY[i] < y && polyY[j] >= y
                || polyY[j] < y && polyY[i] >= y)
                && (polyX[i] <= x || polyX[j] <= x))
                {
                    if (polyX[i] +
                        (y - polyY[i]) /
                        (polyY[j] - polyY[i]) *
                        (polyX[j] - polyX[i]) < x)
                    {
                        oddNodes = !oddNodes;
                    }
                }
                j = i;
            }

            return oddNodes;
        }
    }
}
